package com.ytktt.study.week9.task3.rpcfx.registry;

import com.ytktt.study.week9.task3.rpcfx.enums.ErrResponseEnum;
import com.ytktt.study.week9.task3.rpcfx.exception.RpcfxException;
import com.ytktt.study.week9.task3.rpcfx.properties.RegistryProperties;
import com.ytktt.study.week9.task3.rpcfx.lb.LoadBalancer;
import com.ytktt.study.week9.task3.rpcfx.router.Router;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 注册中心配置
 *
 * @author ytk
 */
@Configuration
@EnableConfigurationProperties(RegistryProperties.class)
public class RegistryConfig {

    @Bean
    @ConditionalOnProperty(prefix = RegistryProperties.PREFIX, name = "type", havingValue = "zookeeper", matchIfMissing = true)
    public Registry registry(RegistryProperties registryProperties, Router router, LoadBalancer loadBalancer) {
        this.judgeUrl(registryProperties);
        try {
            return new ZookeeperRegistry(registryProperties, router, loadBalancer);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RpcfxException(ErrResponseEnum.UNKNOWN_ERROR);
        }
    }

    private void judgeUrl(RegistryProperties registryProperties) {
        if (StringUtils.isBlank(registryProperties.getUrl())) {
            throw new RpcfxException(ErrResponseEnum.REGISTRY_URL_IS_EMPTY_ERROR);
        }
    }

}
